package aerouacmsla.interfazDeUsuario;

import aerouacmsla.DataBD;
import aerouacmsla.procedimientos.BDConexion;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import javax.swing.Timer;

/**
 *
 * @author Marco
 */
public class FirstRun extends javax.swing.JDialog {

    private BDConexion pruebaConexion;
    private DataBD miData = new DataBD();
    private int intentos = 0;
    private int status = 0;

    private Timer timerStatus = new Timer (500, new ActionListener () {
                public void actionPerformed(ActionEvent e) {
                    if (getIntentos() != 3) {
                        if (getStatus() != 1) {
                            if (getPruebaConexion().estadoDeLaConexion()) {
                                setStatus(1);
                                labelEstado.setText("Conexion Exitosa");
                                botonGuardar.setEnabled(true);
                                campoDireccionIP.setEditable(false);
                                //campoNombreBD.setEditable(false);
                                campoNombreUsuario.setEditable(false);
                                campoPassClave.setEditable(false);
                                timerStatus.stop();
                            } else {
                                setIntentos(getIntentos() + 1);
                            }
                        }
                    }
                    else {
                        labelEstado.setText("Conexion Fallida");
                        labelEstado.setBusy(false);
                        setIntentos(0);
                        setStatus(0);
                        timerStatus.stop();
                    }
                }
            });

    public FirstRun() {
        initComponents();
        this.setModal(true);
        Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
        setLocation(d.width / 2 - getSize().width / 2 , d.height / 2 - getSize().height / 2);
        this.setVisible(true);
    }
    public FirstRun(DataBD datosConexion) {
        initComponents();
        Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
        setLocation(d.width / 2 - getSize().width / 2 , d.height / 2 - getSize().height / 2);
        this.setModal(true);
        this.setVisible(true);
        setMiData(datosConexion);
    }

    public int getIntentos() {
        return intentos;
    }

    public void setIntentos(int intentos) {
        this.intentos = intentos;
    }

    public BDConexion getPruebaConexion() {
        return pruebaConexion;
    }

    public void setPruebaConexion(BDConexion pruebaConexion) {
        this.pruebaConexion = pruebaConexion;
    }

    public int getStatus() {
        return status;
    }

    public void setStatus(int status) {
        this.status = status;
    }

    public DataBD getMiData() {
        return miData;
    }

    public void setMiData(DataBD miData) {
        this.miData = miData;
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        topPanel = new javax.swing.JPanel();
        jLabel3 = new javax.swing.JLabel();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        campoDireccionIP = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();
        campoNombreBD = new javax.swing.JTextField();
        jLabel5 = new javax.swing.JLabel();
        campoNombreUsuario = new javax.swing.JTextField();
        jLabel6 = new javax.swing.JLabel();
        campoPassClave = new javax.swing.JPasswordField();
        jLabel7 = new javax.swing.JLabel();
        botonProbarConexion = new javax.swing.JButton();
        botonGuardar = new javax.swing.JButton();
        labelEstado = new org.jdesktop.swingx.JXBusyLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("FirstRun");
        setResizable(false);

        topPanel.setBackground(new java.awt.Color(51, 51, 51));

        jLabel3.setFont(new java.awt.Font("Tahoma", 0, 18));
        jLabel3.setForeground(new java.awt.Color(255, 255, 255));
        jLabel3.setText("First Run");

        javax.swing.GroupLayout topPanelLayout = new javax.swing.GroupLayout(topPanel);
        topPanel.setLayout(topPanelLayout);
        topPanelLayout.setHorizontalGroup(
            topPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(topPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel3)
                .addContainerGap(339, Short.MAX_VALUE))
        );
        topPanelLayout.setVerticalGroup(
            topPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(topPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel3)
                .addContainerGap(33, Short.MAX_VALUE))
        );

        jLabel1.setText("Esta es la primera vez que inicia el programa procederemos con la configuracion");

        jLabel2.setText("Recuerde que primero debe instalar y configurar el servidor");

        campoDireccionIP.setText("localhost");

        jLabel4.setText("Direccion IP del Servidor");

        campoNombreBD.setEditable(false);
        campoNombreBD.setText("project_aerouac");

        jLabel5.setText("Nombre de la Base de Datos");

        campoNombreUsuario.setText("root");

        jLabel6.setText("Nombre de Usuario del Servidor MySQL");

        campoPassClave.setText("123456");

        jLabel7.setText("Contraseña del Servidor MySQL");

        botonProbarConexion.setText("Probar Conexion");
        botonProbarConexion.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                botonProbarConexionMouseClicked(evt);
            }
        });

        botonGuardar.setText("Guardar Configuracion");
        botonGuardar.setEnabled(false);
        botonGuardar.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                botonGuardarMouseClicked(evt);
            }
        });

        labelEstado.setText("???");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(topPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel1)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(10, 10, 10)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel2)
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                    .addComponent(jLabel7)
                                    .addComponent(jLabel6)
                                    .addComponent(jLabel5)
                                    .addComponent(jLabel4))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                    .addComponent(campoNombreBD)
                                    .addComponent(campoDireccionIP, javax.swing.GroupLayout.DEFAULT_SIZE, 198, Short.MAX_VALUE)
                                    .addComponent(campoNombreUsuario)
                                    .addComponent(campoPassClave))))))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(100, Short.MAX_VALUE)
                .addComponent(labelEstado, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(botonGuardar)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(botonProbarConexion)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(topPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel2)
                .addGap(31, 31, 31)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(campoDireccionIP, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel4))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(campoNombreBD, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel5))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(campoNombreUsuario, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel6))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(campoPassClave, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel7))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 33, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(botonProbarConexion)
                    .addComponent(botonGuardar)
                    .addComponent(labelEstado, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void botonProbarConexionMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_botonProbarConexionMouseClicked
        // TODO comprobar que se haga una conexion exitosa
        BDConexion conexionDePrueba = new BDConexion(
                campoDireccionIP.getText(), campoNombreBD.getText(), campoNombreUsuario.getText(), new String(campoPassClave.getPassword()));
        setPruebaConexion(conexionDePrueba);
        labelEstado.setBusy(true);
        timerStatus.start();
    }//GEN-LAST:event_botonProbarConexionMouseClicked

    private void botonGuardarMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_botonGuardarMouseClicked
        if (labelEstado.getText().equalsIgnoreCase("conexion exitosa")){
            //TODO escribir a archivo
            miData.setHost(campoDireccionIP.getText());
            miData.setBdName(campoNombreBD.getText());
            miData.setUsuario(campoNombreUsuario.getText());
            miData.setClave(new String(campoPassClave.getPassword()));
            FileOutputStream file;
            ObjectOutputStream output;
            try {
                String pathHome = System.getProperty("user.home");
                File carpeta = new File(pathHome + "\\DataMSLA");
                carpeta.mkdir();
                file = new FileOutputStream(pathHome + "\\DataMSLA\\DataConexion.config");
                output = new ObjectOutputStream(file);
                output.writeObject(miData);
                this.dispose();
            } catch (IOException iOException) {
                System.out.println("Error al guardar datos");
            }
        }
    }//GEN-LAST:event_botonGuardarMouseClicked


    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new FirstRun().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton botonGuardar;
    private javax.swing.JButton botonProbarConexion;
    private javax.swing.JTextField campoDireccionIP;
    private javax.swing.JTextField campoNombreBD;
    private javax.swing.JTextField campoNombreUsuario;
    private javax.swing.JPasswordField campoPassClave;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private org.jdesktop.swingx.JXBusyLabel labelEstado;
    private javax.swing.JPanel topPanel;
    // End of variables declaration//GEN-END:variables

}
